package com.incar.chuxing.utils;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;


import com.incar.chuxing.R;
import com.incar.chuxing.api.UrlConstant;
import com.incar.chuxing.utils.Dialogs.InCarDialog;
import com.incar.chuxing.utils.Toast.ToastCompat;

import java.io.File;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * Created by Michael Pi on 2016/10/18.
 */
public class VerControlUtils {

    private Context mContext;
    /*下载文件地址*/
    public static String saveFileName;
    private UpdateManager updateManager;

    public VerControlUtils(Context mContext) {
        this.mContext = mContext;
    }

    public String getVersionName() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return "";
    }

    public int getVersionCode() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return 0;
    }


    /**
     * @param curVersionName 服务器最新的版本号（如1.0.2）
     * @param forceUpdate    1强制更新，2非强制
     */
    public void update(String curVersionName, String forceUpdate, String updateInfo, String updateTitle) {
        String[] curCodeArray = curVersionName.split("\\.");
        StringBuilder curVersionCodeStr = new StringBuilder();
        for (int i = 0; i < curCodeArray.length; i++) {
            curVersionCodeStr.append(curCodeArray[i]);
        }
        //服务器版本号
        int curVersionCode = Integer.parseInt(curVersionCodeStr + "");
        //要下载的apk名
        String apkName = "KuaituchuxingV" + curVersionName + ".apk";
        String updateUrl = UrlConstant.Request.DOWNLOAD_APK + apkName;
        //是否需要更新
        if (curVersionCode > getVersionCode()) {
            saveFileName = SDCardUtils.getSDCardPrivateFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS) + File.separator + apkName;
            updateManager = new UpdateManager(mContext);
            //强制更新
            if (forceUpdate.equals("1")) {
                //强制更新,检查是否已下载新版本安装包
                if (SDCardUtils.isFileExist(saveFileName)) {
                    PackageManager pm = mContext.getPackageManager();
                    PackageInfo info = pm.getPackageArchiveInfo(saveFileName, PackageManager.GET_ACTIVITIES);
                    if (info != null) {
                        int versionCode = info.versionCode; //本地已有的安装包的版本
                        //比较已下载到本地的apk安装包，与服务器上apk安装包的版本号是否一致
                        if (curVersionCode == versionCode) {
                            //是最新的apk,弹出框提示用户安装(之前下载过)
                            forceUpdateInstallDownloaded(updateUrl, apkName, updateTitle);
                        } else {
                            forceUpdateInstall(updateUrl, apkName, updateInfo, updateTitle);
                        }
                    } else {//安装包存在，但没有获取到版本号（没有下载完毕导致获取不到）
                        //移除之前的DownloadManager的下载任务，重新下载
                        ((DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE)).remove(SharedPreferencesUtils.getInstance(mContext).getLongValue("downloadId"));
                        SDCardUtils.removeFileFromSDCard(saveFileName);
                        forceUpdateInstall(updateUrl, apkName, updateInfo,updateTitle);
                    }
                    //强制更新,没有下载好安装包
                } else {
                    forceUpdateInstall(updateUrl, apkName, updateInfo,updateTitle);
                }

                //推荐更新
            } else {
                //推荐更新，WiFi下，通知栏下载，下载完通知提醒点击安装
                // 非WiFi下，弹出对话框，用户选择是否更新，通知栏下载，下载完通知提醒点击安装
                //存在安装包
                if (SDCardUtils.isFileExist(saveFileName)) {
                    PackageManager pm = mContext.getPackageManager();
                    PackageInfo info = pm.getPackageArchiveInfo(saveFileName, PackageManager.GET_ACTIVITIES);
                    if (info != null) {
                        int versionCode = info.versionCode; //本地已有的安装包的版本
                        //比较已下载到本地的apk安装包，与服务器上apk安装包的版本号是否一致
                        if (curVersionCode == versionCode) {
                            //是最新的apk,弹出框提示用户安装(之前下载过)
                            recommendUpdateDownloaded(updateTitle);
                        } else {
                            //存在的安装包不是最新的，删除旧的apk，重新下载
                            SDCardUtils.removeFileFromSDCard(saveFileName);
                            if (NetUtils.isConnectedByWifi(mContext)) {
                                updateManager.downLoadApk(updateUrl, apkName, UpdateManager.SHOW_NOTIFICATION_DONE);
                            } else {
                                recommendUpdateInstall(updateUrl, apkName, updateInfo,updateTitle);
                            }
                        }
                    } else {  //安装包存在，但没有获取到版本号（没有下载完毕导致获取不到）
                        //移除之前的DownloadManager的下载任务，重新下载
                        ((DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE)).remove(SharedPreferencesUtils.getInstance(mContext).getLongValue("downloadId"));
                        SDCardUtils.removeFileFromSDCard(saveFileName);
                        if (NetUtils.isConnectedByWifi(mContext)) {
                            updateManager.downLoadApk(updateUrl, apkName, UpdateManager.SHOW_NOTIFICATION_DONE);
                        } else {
                            recommendUpdateInstall(updateUrl, apkName, updateInfo,updateTitle);
                        }
                    }
                } else {
                    //不存在安装包
                    if (NetUtils.isConnectedByWifi(mContext)) {
                        updateManager.downLoadApk(updateUrl, apkName, UpdateManager.SHOW_NOTIFICATION_DONE);
                    } else {
                        recommendUpdateInstall(updateUrl, apkName, updateInfo,updateTitle);
                    }
                }
            }
        }
    }

    /**
     * 推荐升级对话框，下载apk
     *
     * @param
     */
    private void forceUpdateInstall(final String updateUrl, final String apkName, String updateInfo, String updateTitle) {
        final InCarDialog inCarDialog = new InCarDialog(mContext);
        inCarDialog.setTitle(mContext.getString(R.string.dialogTitle));
        inCarDialog.setMessage(updateInfo);
        inCarDialog.setYesOnclickListener("点我升级", new InCarDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                //强制升级，存在的包不是最新的，删除旧的apk
                SDCardUtils.removeFileFromSDCard(saveFileName);
                //下载新的apk，不显示下载进度通知，显示ProgressDialog进度
                updateManager.downLoadApk(updateUrl, apkName, UpdateManager.SHOW_PROGRESS_DIALOG);
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                ToastCompat.makeText(mContext, "您的应用太老了，需要升级才能使用", Toast.LENGTH_LONG).show();
            }
        });
        inCarDialog.setCancelable(false);
        inCarDialog.show();
    }

    /**
     * 强制升级对话框，已经下载好apk
     *
     * @param
     */
    private void forceUpdateInstallDownloaded(final String updateUrl, final String apkName, String updateTitle) {
        final InCarDialog inCarDialog = new InCarDialog(mContext);
        inCarDialog.setTitle(updateTitle);
        inCarDialog.setMessage("新版本安装包已为您准备好啦，请升级吧！");
        inCarDialog.setYesOnclickListener("点我升级", new InCarDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                installApk();
            }
        });
        inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                ToastCompat.makeText(mContext, "您的应用太老了，需要升级才能使用", Toast.LENGTH_LONG).show();
            }
        });
        inCarDialog.setCancelable(false);
        inCarDialog.show();
    }

    /**
     * 推荐升级对话框，下载apk
     *
     * @param
     */
    private void recommendUpdateInstall(final String updateUrl, final String apkName, String updateInfo, String updateTitle) {
        final InCarDialog inCarDialog = new InCarDialog(mContext);
        inCarDialog.setTitle(updateTitle);
        inCarDialog.setMessage(updateInfo);
        inCarDialog.setYesOnclickListener("现在升级", new InCarDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                updateManager.downLoadApk(updateUrl, apkName, UpdateManager.SHOW_NOTIFICATION_DOWNLOADING);
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setNoOnclickListener("推迟升级", new InCarDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setCancelable(false);
        inCarDialog.show();
    }

    /**
     * 推荐升级对话框，已经下载好apk
     *
     * @param
     */
    private void recommendUpdateDownloaded(String updateTitle) {
        final InCarDialog inCarDialog = new InCarDialog(mContext);
        inCarDialog.setTitle(updateTitle);
        inCarDialog.setMessage("新版本安装包已为您准备好啦，请升级吧！");
        inCarDialog.setYesOnclickListener("现在安装", new InCarDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                installApk();
            }
        });
        inCarDialog.setNoOnclickListener("推迟安装", new InCarDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setCancelable(false);
        inCarDialog.show();
    }

    private void installApk() {
        File apkfile = new File(saveFileName);
        if (apkfile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkFileUri = Uri.fromFile(apkfile);

            /*Uri apkFileUri = FileProvider.getUriForFile(mContext, "com.incar.fileprovider", apkfile);*/
            intent.setDataAndType(apkFileUri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
            SharedPreferencesUtils.getInstance(mContext).removeValue("downloadId");
        }
    }
}

